import {ipcMain} from 'electron';
import {UserService} from '../db';
import {User} from '../db';
import fs from 'fs';
import DatabaseManager from '../db/DatabaseManager';

// 创建用户服务实例
const userService = new UserService();

/**
 * 注册数据库操作的IPC处理函数
 */
export function setupDbHandlers() {
  // 用户相关操作

  // 获取用户列表
  ipcMain.handle('db:user:list', async (_, page: number = 1, pageSize: number = 10, condition: any = {}) => {
    try {
      return userService.getUsers(page, pageSize, condition);
    } catch (error) {
      console.error('获取用户列表失败:', error);
      throw error;
    }
  });

  // 获取用户详情
  ipcMain.handle('db:user:get', async (_, id: number) => {
    try {
      return userService.getById(id);
    } catch (error) {
      console.error('获取用户详情失败:', error);
      throw error;
    }
  });

  // 创建用户
  ipcMain.handle('db:user:create', async (_, userData: Partial<User>) => {
    try {
      // 检查用户名是否存在
      const existingUser = userService.findByUsername(userData.username!);
      if (existingUser) {
        throw new Error('用户名已存在');
      }

      // 设置创建时间和更新时间
      userData.createTime = Math.floor(Date.now() / 1000);
      userData.updateTime = userData.createTime;

      const userId = userService.insert(userData);
      return { id: userId };
    } catch (error) {
      console.error('创建用户失败:', error);
      throw error;
    }
  });

  // 更新用户
  ipcMain.handle('db:user:update', async (_, userData: Partial<User>) => {
    try {
      if (!userData.id) {
        throw new Error('更新用户信息需要提供用户ID');
      }

      // 如果要更新用户名，检查是否存在同名用户
      if (userData.username) {
        const existingUser = userService.findByUsername(userData.username);
        if (existingUser && existingUser.id !== userData.id) {
          throw new Error('用户名已存在');
        }
      }

      const result = userService.updateUser(userData);
      return { success: result > 0 };
    } catch (error) {
      console.error('更新用户失败:', error);
      throw error;
    }
  });

  // 删除用户
  ipcMain.handle('db:user:delete', async (_, id: number) => {
    try {
      const result = userService.deleteById(id);
      return { success: result > 0 };
    } catch (error) {
      console.error('删除用户失败:', error);
      throw error;
    }
  });

  // 搜索用户
  ipcMain.handle('db:user:search', async (_, keyword: string, page: number = 1, pageSize: number = 10) => {
    try {
      return userService.searchUsers(keyword, page, pageSize);
    } catch (error) {
      console.error('搜索用户失败:', error);
      throw error;
    }
  });

  // 数据库管理相关操作

  // 获取数据库文件信息
  ipcMain.handle('db:info:file', async () => {
    try {
      // 获取数据库文件路径
      const dbInstance = DatabaseManager; // 直接使用导入的实例
      const dbPath = dbInstance.getDatabasePath(); // 使用公共方法获取路径

      if (!dbPath || !fs.existsSync(dbPath)) {
        throw new Error('数据库文件不存在');
      }

      // 获取文件状态信息
      const stats = fs.statSync(dbPath);

      return {
        path: dbPath,
        size: formatFileSize(stats.size),
        createTime: stats.birthtime,
        modifyTime: stats.mtime,
        exists: true
      };
    } catch (error) {
      console.error('获取数据库文件信息失败:', error);
      throw error;
    }
  });

  // 通用数据库操作

  // 执行自定义SQL查询
  ipcMain.handle('db:query', async (_, sql: string, params: any[] = []) => {
    try {
      return userService.query(sql, params);
    } catch (error) {
      console.error('执行SQL查询失败:', error);
      throw error;
    }
  });

  // 执行自定义SQL更新
  ipcMain.handle('db:execute', async (_, sql: string, params: any[] = []) => {
    try {
      const result = userService.execute(sql, params);
      return {
        changes: result.changes,
        lastInsertRowid: result.lastInsertRowid
      };
    } catch (error) {
      console.error('执行SQL更新失败:', error);
      throw error;
    }
  });
}

/**
 * 移除数据库操作的IPC处理函数
 */
export function removeDbHandlers() {
  ipcMain.removeHandler('db:user:list');
  ipcMain.removeHandler('db:user:get');
  ipcMain.removeHandler('db:user:create');
  ipcMain.removeHandler('db:user:update');
  ipcMain.removeHandler('db:user:delete');
  ipcMain.removeHandler('db:user:search');
  ipcMain.removeHandler('db:info:file');
  ipcMain.removeHandler('db:query');
  ipcMain.removeHandler('db:execute');
}

/**
 * 格式化文件大小
 * @param bytes 字节数
 * @returns 格式化后的大小字符串
 */
function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B';

  const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
  const i = Math.floor(Math.log(bytes) / Math.log(1024));

  return parseFloat((bytes / Math.pow(1024, i)).toFixed(2)) + ' ' + units[i];
}
